//
//  TTGoodsListView.m
//  TaoTuo
//
//  Created by admin on 2019/8/19.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTGoodsListView.h"
#import "TTHomeListViewCell.h"
#import "LLUpDownArrowView.h"
#import "LLConditionalView.h"
#import "TTGoodsDetailViewController.h"
#import "TTHomeGridViewCell.h"
#import "TTScreeningView.h"
#import "TTEmptyView.h"

#define topH 36

@interface TTGoodsListView ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, LLConditionalViewDelegate/*, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate*/>
{
    NSString *finishedProductKey;//成品
    NSString *colorKey;   // 颜色
    NSString *jdKey;      // 净度
    NSString *cutKey;    // 切工
    
    MJRefreshNormalHeader *mjHeader;
    MJRefreshBackNormalFooter *mjFooter;
}

@property (nonatomic, strong) UICollectionViewFlowLayout *gridLayout;   // 网格
/// 综合按钮
@property (nonatomic, strong) UIButton *collectBtn;
@property (nonatomic, strong) LLConditionalView *conditionView;

//@property (nonatomic, strong) TTScreeningView *screeningView;   // 筛选页面

@property (nonatomic, copy) NSString *cellIdentifier;
@property (nonatomic, copy) NSString *gridCellID;
@property (nonatomic, assign) int page;



@property (nonatomic, strong) NSMutableArray<TTHomeListModel *> *dataArray;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, strong) NSMutableDictionary *paramsDic;

@property (nonatomic, strong) NSMutableDictionary *originDic;  ///原参数
@property (nonatomic, strong) LLAnimationAlertView *alertView;
/// 无数据时的空view
@property (nonatomic, strong) TTEmptyView *emptyView;
/// 猜你喜欢
@property (nonatomic, strong) UIView *guessYouLikeView;

@end

@implementation TTGoodsListView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.page = 1;
        
        self.gridLayout = [[UICollectionViewFlowLayout alloc] init];
        self.gridLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        self.gridLayout.minimumLineSpacing = 10;
        self.gridLayout.minimumInteritemSpacing = 10;
        self.gridLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        finishedProductKey = @"param.finishedProduct";
        colorKey = @"param.sStoneColor";
        jdKey = @"param.sStoneClarity";
        cutKey = @"param.sStoneCut";
        
        
        self.cellIdentifier = @"goods_list_cell";
        self.gridCellID = @"goods_grid_cell";
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, topH, self.width, self.height - topH) collectionViewLayout:self.gridLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = UIColorHex(#F5F5F5);
        [_collectionView registerClass:[TTHomeListViewCell class] forCellWithReuseIdentifier:self.cellIdentifier];
        [_collectionView registerClass:[TTHomeGridViewCell class] forCellWithReuseIdentifier:self.gridCellID];
    //    _collectionView.emptyDataSetDelegate = self;
    //    _collectionView.emptyDataSetSource = self;
        
        [self addSubview:_collectionView];
        /// 显示加载中的view
        [LLLoadingViewManager showLoadingViewInView:self.collectionView];
        
        @weakify(self)
        mjHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            @strongify(self)
            [self getFirstPageData];
        }];
        self.collectionView.mj_header = mjHeader;

        mjFooter = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            @strongify(self)
            [self loadMoreData];
        }];
        self.collectionView.mj_footer = mjFooter;
        
        // 添加上部分view
        _collectBtn = [UIButton createButtonWithTitle:@"综合" normalTitleColor:UIColorHex(#333333) selectedTitleColor:UIColorHex(#8B57E6) titleFont:[UIFont boldSystemFontOfSize:14] backgroundColor:nil cornerRadius:0 target:self action:@selector(clickCollectBtn:)];
        _collectBtn.frame = CGRectMake(0, 0, self.width / 4.0, topH);
        _collectBtn.selected = YES;
        [self addSubview:_collectBtn];
        
        _conditionView = [[LLConditionalView alloc] initWithFrame:CGRectMake(_collectBtn.right, 0, self.width - _collectBtn.width, topH) titlesArray:@[@"价格", @"销量"] totalCount:0];
    //    _conditionView.backgroundColor = UIColorHex(F0F4F7);
        _conditionView.delegate = self;
        [self addSubview:_conditionView];
        
        // 上面圆角
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.width, topH) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
        CAShapeLayer *layer = [CAShapeLayer layer];
        layer.fillColor = UIColorHex(#F5F5F5).CGColor;
        layer.path = path.CGPath;
        [self.layer insertSublayer:layer atIndex:0];
        
        ///点击筛选按钮
        _conditionView.screeningBlock = ^{
            @strongify(self)
            self.alertView = [LLAnimationAlertView animationAlertViewWithView:self.leftFiltrateView animationType:AnimationFromRight tapBgDismiss:YES inView:[LLRouteTool getCurrentNavigationController].view];
            ///点击空白处消失
            self.alertView.dismissBlock = ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"dismissActionNotify" object:nil];
            };
            
        };
        
        
    }
    return self;
}

- (void)searchDatasWithParams:(NSDictionary *)paramsDic
{
    [self setType:self.type params:paramsDic];
    if (self.searchParamsChangedBlock) {
        self.searchParamsChangedBlock(self.paramsDic);
    }
}

- (void)setType:(NSInteger)type params:(nonnull NSDictionary *)paramsDic
{
//    self.type = type;
    self.paramsDic = paramsDic.mutableCopy;
    
    // 设置参数
    [self.paramsDic setObject:@(self.page) forKey:@"param.pageIndex"];
    [self.paramsDic setObject:@(40) forKey:@"param.pageSize"];
    
//    NSString *typeStr = [NSString stringWithFormat:@"%ld", (long)type];
//    NSDictionary *dic = @{
//                          @"0" : @"", @"1" : @"新款", @"2" : @"畅销", @"3" : @"经典", @"4" : @"爆款",
//                          };
//    [self.paramsDic setObject:dic[typeStr] forKey:@"param.productType"];
    
    
    
//    //如果选了产品
//    int screeningCount = 0;
//    if ([self.paramsDic.allKeys containsObject:finishedProductKey]) {
//        screeningCount = [self.paramsDic[finishedProductKey] intValue] == 0 ? screeningCount : (screeningCount + 1);
//    }
//    if ([self.paramsDic.allKeys containsObject:colorKey]) {
//        screeningCount++;
//    }
//    if ([self.paramsDic.allKeys containsObject:jdKey]) {
//        screeningCount++;
//    }
//    if ([self.paramsDic.allKeys containsObject:cutKey]) {
//        screeningCount++;
//    }
//    self.conditionView.screeningCount = screeningCount;
    
    
    
    [self getFirstPageData];
}

- (void)setHiddenScreening:(BOOL)hiddenScreening
{
    self.conditionView.hiddenScreening = hiddenScreening;
}

/// 点击了综合按钮
- (void)clickCollectBtn:(UIButton *)sender
{
    sender.selected = YES;
    [self.conditionView cancelSelected];
    [self.paramsDic removeObjectForKey:@"param.orderBy"];
    [self.paramsDic removeObjectForKey:@"param.isAsc"];
    ///保留原参数
    self.originDic = self.paramsDic.mutableCopy;
    self.page = 1;
    [self getNetworkDataWithLoadView:self.collectionView];
}

#pragma mark - LLConditionalViewDelegate
- (void)conditionalView:(LLConditionalView *)conditionalView title:(NSString *)title isAsc:(BOOL)isAsc
{
    self.collectBtn.selected = NO;
    
    NSDictionary *dic = @{
                          @"价格" : @"TotalPrice",
                          @"销量" : @"SalesVolume",
                          };
    NSString *ascStr = isAsc ? @"true" : @"false";
    
    [self.paramsDic setObject:dic[title] forKey:@"param.orderBy"];
    [self.paramsDic setObject:ascStr forKey:@"param.isAsc"];
    ///保留原参数
    self.originDic = self.paramsDic.mutableCopy;
    
    self.page = 1;
    [self getNetworkDataWithLoadView:self.collectionView];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTHomeListModel *model = self.dataArray[indexPath.row];
    // 网格
    TTHomeGridViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:self.gridCellID forIndexPath:indexPath];
    cell.model = model;
    return cell;
    
//    if (self.collectionView.collectionViewLayout == self.listLayout) {
//        // 列表
//        TTHomeListViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:self.cellIdentifier forIndexPath:indexPath];
//        cell.model = model;
//        return cell;
//    } else {
//        // 网格
//        TTHomeGridViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:self.gridCellID forIndexPath:indexPath];
//        cell.model = model;
//        return cell;
//    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTHomeListModel *model = self.dataArray[indexPath.row];
    TTGoodsDetailViewController *detailVC = [[TTGoodsDetailViewController alloc] initWithStyleLibraryId:model.StyleLibraryId model:model];
//    detailVC.styleLibraryId = model.StyleLibraryId;
    detailVC.otherParams = self.paramsDic;
    [self.viewController.navigationController pushViewController:detailVC animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 网格
    return CGSizeMake((self.width - 30) * 0.5, 175 * kScale + 60);
    
//    if (self.collectionView.collectionViewLayout == self.listLayout) {
//        // 列表
//        TTHomeListModel *model = self.dataArray[indexPath.row];
//        NSArray *contentArray = model.DescriptionList;
//        CGFloat h = ceil(contentArray.count / 2.0) * 22 + 94;
//        h = h < 145 ? 145 : h;
//        return CGSizeMake(self.width, h * kScale + 20);
//
//    } else {
//        // 网格
//        return CGSizeMake((self.width - 25) * 0.5, 175 * kScale + 60);
//    }
    
}

- (void)getFirstPageData
{
    self.page = 1;
    [self getNetworkDataWithLoadView:nil];
}

- (void)loadMoreData
{
    self.page++;
    [self getNetworkDataWithLoadView:nil];
}

- (void)getNetworkDataWithLoadView:(UIView *)loadView
{
    NSString *searchStr = self.originDic[@"param.searchKey"] ? : self.paramsDic[@"param.searchKey"];
    NSDictionary *allDic = @{
        @"param.pageSize" : @40,
        @"param.sourceType" : @3,
        @"param.pageIndex" : @(self.page),
        @"param.searchKey" : searchStr,
    };
    
    [self.paramsDic setObject:@(self.page) forKey:@"param.pageIndex"];
    
    ///保留原参数
    self.originDic = self.paramsDic.mutableCopy;
    
    [self.paramsDic removeObjectForKey:@"param.searchKey"];
    
    NSDictionary *requestDic = self.isAll ? allDic : self.paramsDic;
    
    [[LLNetworkManagerTool sharedManager] postUrlString:queryList_api parameters:requestDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (self.page == 1) {
            [self.dataArray removeAllObjects];
        }
        // 隐藏加载中的view
        [LLLoadingViewManager hiddenLoadingViewInView:self.collectionView];
        
        NSArray *arr = responseObject[@"Data"];
        self.conditionView.totalCount = [responseObject[@"TotalCount"] intValue];
        
        for (NSDictionary *dic in arr) {
            TTHomeListModel *model = [TTHomeListModel modelWithJSON:dic];
            [self.dataArray addObject:model];
        }
        
        [self.collectionView.mj_header endRefreshing];
        if (arr.count < 40) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.collectionView.mj_footer endRefreshing];
        }
        
        if (self.dataArray.count == 0) {
            self.collectionView.mj_header = nil;
            self.collectionView.mj_footer = nil;
            self.emptyView.hidden = NO;
            [self.collectionView addSubview:self.emptyView];
            self.gridLayout.sectionInset = UIEdgeInsetsMake(self.emptyView.height + self.guessYouLikeView.height + 10, 10, 10, 10);
            self.guessYouLikeView.hidden = NO;
            // 请求猜你喜欢数据
            [self requestCategoryList];
        } else {
            self.collectionView.mj_header = self->mjHeader;
            self.collectionView.mj_footer = self->mjFooter;
            self.emptyView.hidden = YES;
            [self.emptyView removeFromSuperview];
            self.gridLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
            self.guessYouLikeView.hidden = YES;
            [self.collectionView reloadData];
        }

        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        // 隐藏加载中的view
        [LLLoadingViewManager hiddenLoadingViewInView:self.collectionView];
        
    } showLoadingInView:loadView];
}

// 查询猜你喜欢数据
- (void)requestCategoryList
{
    NSDictionary *dic = @{
        @"param.categoryName" : self.paramsDic[@"param.categoryName"],
        @"param.pageIndex" : @1,
        @"param.pageSize" : @6,
        @"param.sourceType" : self.paramsDic[@"param.sourceType"]
    };
    [[LLNetworkManagerTool sharedManager] postUrlString:queryList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *arr = responseObject[@"Data"];
        for (NSDictionary *dic in arr) {
            TTHomeListModel *model = [TTHomeListModel modelWithJSON:dic];
            [self.dataArray addObject:model];
        }
        
        [self.collectionView addSubview:self.guessYouLikeView];
        
        [self.collectionView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        NSLog(@"er =%@", error);
    } showLoadingInView:nil];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if (scrollView.contentOffset.y == 0) {
        if (self.scrollToTopBlock) {
            self.scrollToTopBlock();
        }
    }
}

///停止拖拽可能还会滑动一段距离
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.scrollEnd) {
        self.scrollEnd(scrollView.contentOffset.y);
    }
}

///已经停止了
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.scrollEnd) {
        self.scrollEnd(scrollView.contentOffset.y);
    }
}


#pragma mark - JXCategoryListContentViewDelegate
- (UIView *)listView
{
    return self;
}

//#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
//{
//    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:@"暂无数据" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:18], NSForegroundColorAttributeName : UIColorHex(333333)}];
//    return attr;
//}
//
//- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
//{
//    return [UIImage imageNamed:@"nodata"];
//}

- (NSMutableArray<TTHomeListModel *> *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (TTLeftFiltrateView *)leftFiltrateView
{
    if (!_leftFiltrateView) {
        _leftFiltrateView = [[TTLeftFiltrateView alloc] initWithFrame:CGRectMake(0, 0, self.width * 5 / 6, SCREEN_HEIGHT)];
        @weakify(self)
        _leftFiltrateView.clickSearchBlock = ^(NSDictionary * _Nonnull dic) {
            @strongify(self)
            [self searchDatasWithParams:dic];
        };
    }
    [_leftFiltrateView setSelectItemsWithParamDic:self.paramsDic];
    return _leftFiltrateView;
}

//- (TTScreeningView *)screeningView
//{
//    if (!_screeningView) {
//        _screeningView = [[TTScreeningView alloc] initWithFrame:CGRectMake(0, 0, self.width * 4 / 5, SCREEN_HEIGHT)];
//
//        [_screeningView setSelectItemsWithDic:self.paramsDic];
//
//        @weakify(self)
//        // 搜索
//        _screeningView.confirmBlock = ^(NSDictionary * _Nonnull dic) {
//            @strongify(self)
//            if (self == nil) return;
//
//            self.paramsDic = self.originDic.mutableCopy;
//
//            if (dic.count > 0) {
//                [self.paramsDic addEntriesFromDictionary:dic];
//            }
//            if (![dic.allKeys containsObject:self->finishedProductKey]) {
//                [self.paramsDic removeObjectForKey:self->finishedProductKey];
//            }
//            if (![dic.allKeys containsObject:self->colorKey]) {
//                [self.paramsDic removeObjectForKey:self->colorKey];
//            }
//            if (![dic.allKeys containsObject:self->jdKey]) {
//                [self.paramsDic removeObjectForKey:self->jdKey];
//            }
//            if (![dic.allKeys containsObject:self->cutKey]) {
//                [self.paramsDic removeObjectForKey:self->cutKey];
//            }
//
//            self.conditionView.screeningCount = (int)dic.allKeys.count;
//            self.page = 1;
//            [self getNetworkDataWithLoadView:nil];
//        };
//
//        //重置
//        _screeningView.resetBlock = ^(NSDictionary * _Nonnull dic) {
//            @strongify(self)
//
//            self.paramsDic = self.originDic.mutableCopy;
//            self.conditionView.screeningCount = 0;
//
//        };
//    }
//    return _screeningView;
//}

- (TTEmptyView *)emptyView
{
    if (!_emptyView) {
        _emptyView = [[TTEmptyView alloc] initWithFrame:CGRectMake(0, 0, self.width, 300)];
        _emptyView.imageName = @"zanwushangpin";
        _emptyView.title = @"您搜索的商品暂时无货哦～";
    }
    return _emptyView;
}

- (UIView *)guessYouLikeView
{
    if (!_guessYouLikeView) {
        _guessYouLikeView = [[UIView alloc] initWithFrame:CGRectMake(0, self.emptyView.bottom, self.width, 55)];
        _guessYouLikeView.backgroundColor = UIColor.whiteColor;
        
        UIButton *titleBtn = [UIButton createButtonWithTitle:@"猜你喜欢" titleColor:UIColorHex(#8B57E6) titleFont:[UIFont systemFontOfSize:14] backgroundColor:nil target:nil action:nil];
        [titleBtn setImage:[UIImage imageNamed:@"like"] forState:UIControlStateNormal];
        [_guessYouLikeView addSubview:titleBtn];
        [titleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(_guessYouLikeView);
        }];
        
        UIImageView *leftImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"leftLine"]];
        leftImageView.contentMode = UIViewContentModeScaleAspectFit;
        [_guessYouLikeView addSubview:leftImageView];
        [leftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(titleBtn.mas_left).mas_offset(-10);
            make.centerY.equalTo(_guessYouLikeView);
        }];
        
        UIImageView *rightImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"rightLine"]];
        rightImageView.contentMode = UIViewContentModeScaleAspectFit;
        [_guessYouLikeView addSubview:rightImageView];
        [rightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(titleBtn.mas_right).mas_offset(10);
            make.centerY.equalTo(_guessYouLikeView);
        }];
        
    }
    return _guessYouLikeView;
}

@end
